import { ref, provide, inject } from 'vue';

interface GlobalState {
  username: import('vue').Ref<string>;
  setUsername: (newUsername: string) => void;
}

const createGlobalState = (): GlobalState => {
  const username = ref('');

  const setUsername = (newUsername: string) => {
    username.value = newUsername;
  };

  provide('globalState', {
    username,
    setUsername,
  });

  return {
    username,
    setUsername,
  };
};

const useGlobalState = (): GlobalState => {
  const globalState = inject<GlobalState>('globalState');

  if (!globalState) {
    throw new Error('useGlobalState must be used within a component provided with createGlobalState');
  }

  return globalState;
};

export { createGlobalState, useGlobalState };